
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>添加商品</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi" />
  <link rel="stylesheet" href="${re.contextPath}/plugin/layui/css/layui.css">
  <script type="text/javascript" src="${re.contextPath}/plugin/jquery/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src="${re.contextPath}/plugin/layui/layui.all.js" charset="utf-8"></script>
  <script type="text/javascript" src="${re.contextPath}/plugin/tools/tool.js"></script>
  <meta charset="utf-8" />
  <meta name="renderer" content="webkit" />
  <meta name="renderer" content="webkit|ie-stand|ie-comp" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="format-detection" content="telephone=no" />

  <link rel="stylesheet" href="layui/css/layui.css" />
  <!--[if lt IE 9]>
  <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
  <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->
  <style type="text/css">
    /*您可以将下列样式写入自己的样式表中*/
    .childBody{padding: 15px;}

    /*layui 元素样式改写*/
    .layui-btn-sm{line-height: normal; font-size: 12.5px;}
    .layui-table-view .layui-table-body{min-height: 256px;}
    .layui-table-cell .layui-input.layui-unselect{height: 30px; line-height: 30px;}

    /*设置 layui 表格中单元格内容溢出可见样式*/
    .table-overlay .layui-table-view,
    .table-overlay .layui-table-box,
    .table-overlay .layui-table-body{overflow: visible;}
    .table-overlay .layui-table-cell{height: auto; overflow: visible;}

    /*文本对齐方式*/
    .text-center{text-align: center;}
  </style>

</head>

<body class="childBody">
<form class="layui-form layui-form-pane" id="saveForm" style="margin-left: 20px;">

<!--    <div class="layui-inline">-->
<!--      <label for="orderNo" class="layui-form-label">-->
<!--        <span class="x-red">*</span>编号-->
<!--      </label>-->
<!--      <div class="layui-input-inline">-->
<!--        <input type="text" id="orderNo" value="${id}" name="orderNo" lay-verify="required"  autocomplete="off" class="layui-input">-->
<!--      </div>-->
<!--    </div>-->
    <div class="layui-inline">
      <label for="tbGoodsName" class="layui-form-label">
        <span class="x-red">*</span>商品名称
      </label>
      <div class="layui-input-inline">
          <input type="text" id="tbGoodsName" name="tbGoodsName" lay-verify="goodsName"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
        <label for="fkId" class="layui-form-label">
            <span class="x-red">*</span>商品分类
        </label>
        <div class="layui-input-inline">
            <select name="tbGoodsState" id="tbGoodsState" lay-verify="tbGoodsState" >
            <option value="1">上午区</option>
            <option value="2">下午区</option>
            <option value="3">测试区</option>
        </select>
        </div>
    </div>
    <div class="layui-inline">
      <label for="tbGoodsto" class="layui-form-label">
        <span class="x-red">*</span>归属人编号
      </label>
      <div class="layui-input-inline">
        <input type="text" id="tbGoodsto" name="tbGoodsto" lay-verify="tbGoodsto"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="tbGoodsPrice" class="layui-form-label">
        <span class="x-red">*</span>商品价格
      </label>
      <div class="layui-input-inline">

        <input type="text" id="tbGoodsPrice" name="tbGoodsPrice" lay-verify="tbGoodsPrice"  autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
      <label for="tbGoodsDate" class="layui-form-label">
        <span class="x-red">*</span>上架日期
      </label>
      <div class="layui-input-inline">
        <input type="text" id="tbGoodsDate" name="tbGoodsDate" lay-verify="tbGoodsDate" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
      </div>
    </div>
    <div class="layui-inline">
        <label for="tbGoodsContent" class="layui-form-label">
            <span class="x-red">*</span>商品描述
        </label>
        <div class="layui-input-inline">

            <input type="text" id="tbGoodsContent" name="tbGoodsContent" lay-verify="tbGoodsContent"  autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-inline">
        <button type="button" class="layui-btn" id="test3"><i class="layui-icon"></i>上传文件</button>
        <div class="layui-input-inline">
            <input type="text"  id="tbGoodsPath" name="tbGoodsPath"   lay-verify="tbGoodsPath"
                   autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-inline">
        <button type="button" class="layui-btn" id="test4"><i class="layui-icon"></i>上传文件</button>
        <div class="layui-input-inline">
            <input type="text"  id="tbGoodsPath1" name="tbGoodsPath1"   lay-verify="tbGoodsPath1"
                   autocomplete="off" class="layui-input">
        </div>
    </div>
  </div>
<section class="layui-col-md10" style="margin: 0 auto; float: none;">
  <div class="layui-card">
    <div class="layui-card-body layui-text">
      <div id="action" class="text-center">
          <button  class="layui-btn layui-btn-normal" lay-filter="add" lay-submit="">
              增加
          </button>
        <button type="button" name="btnSave" class="layui-btn" data-type="save"><i class="layui-icon layui-icon-ok-circle"></i>保存</button>
      </div>
    </div>
  </div>

</section>
</form>
<!--recommended script position-->
<script src="layui/layui.js?v=201805080202" charset="utf-8"></script>
<script type="text/javascript">
  //准备视图对象
  window.viewObj = {
    tbData: [{
      sample: '1',
      design: '1',
      material: '1',
      technology: '1',
      handle: '1',
      number: '1',
        weight: '1',
        period: '1',
        foreign_prient: '1',
        foreign_handle: '1'

    }],
    typeData: [
      {id: 1, name: '分类一'},
      {id: 2, name: '分类二'},
      {id: 3, name: '分类三'},
      {id: 4, name: '分类四'}
    ],
    renderSelectOptions: function(data, settings){
      settings =  settings || {};
      var valueField = settings.valueField || 'value',
              textField = settings.textField || 'text',
              selectedValue = settings.selectedValue || "";
      var html = [];
      for(var i=0, item; i < data.length; i++){
        item = data[i];
        html.push('<option value="');
        html.push(item[valueField]);
        html.push('"');
        if(selectedValue && item[valueField] == selectedValue ){
          html.push(' selected="selected"');
        }
        html.push('>');
        html.push(item[textField]);
        html.push('</option>');
      }
      return html.join('');
    }
  };
  function serializeRemoveNull(serStr){
    return serStr.split("&").filter(str => !str.endsWith("=")).join("&");
  }
  function danji() {
    var photos = $("#file").val();
    window.open('/images/'+photos,'','');
  }
  function sub() {
    var dataFrom = serializeRemoveNull($("#saveForm").serialize());
    var tableData= JSON.stringify(table.cache[layTableId]);
    console.log(addTime);
    $.ajax({
      url: "addDemand",
      type: "post",
      data:JSON.parse(dataFrom),
      success: function (data) {
        window.top.layer.msg("保存成功", {icon: 6, offset: 'rb', area: ['120px', '80px'], anim: 2});
        window.parent.location.reload();//刷新父页面
        var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
        parent.layer.close(index);
      },
      error: function () {
        alert("保存失败");
      }
    })
  }
  function checkC(){
    var order = $("#orderNo").val();
    if(order ==""){
      alert("编号不能为空");
      return false;
    }

    return true;
  }
  function serializeToObject(jsonArray){
    var o = {};
    $.each(jsonArray, function() {
      if (o[this.name] !== undefined) {
        if(o[this.name] !== 'LAY_TABLE_INDEX') {
          if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
          }
          o[this.name].push(this.value || '');
        }


      } else {
        o[this.name] = this.value || '';
      }
    });
    return o;
  }

  //layui 模块化引用
  layui.use(['jquery', 'table', 'layer','laydate', 'form','upload'], function(){
    var $ = layui.$, table = layui.table, upload = layui.upload, form = layui.form,laydate=layui.laydate, layer = layui.layer;
    laydate.render({
      elem: '#tbGoodsDate'
      ,trigger: 'click'
    });
      //监听提交
      form.on('submit(add)', function(data){
          layerAjax('save1', data.field, 'showGoodsList');
          return false;
      });
      form.render();
    upload.render({
      elem: '#test3'
      ,url: 'upload'
      ,accept: 'file',
      before: function(obj){
        //预读，不支持ie8
        obj.preview(function(index, file, result){
          $('#demo2').find('img').remove();
          $('#demo2').append('<span class="x-red">已经上传</span>');
        });
      },done: function(res){
        if(!res.flag){
          layer.msg(res.msg,{icon: 5,anim: 6});
        }else{
          console.log(res);
          $("#tbGoodsPath").val(res.msg);
          console.info($('#tbGoodsPath').val());
        }
      }
    });
      upload.render({
          elem: '#test4'
          ,url: 'upload'
          ,accept: 'file',
          before: function(obj){
              //预读，不支持ie8
              obj.preview(function(index, file, result){
                  $('#demo2').find('img').remove();
                  $('#demo2').append('<span class="x-red">已经上传</span>');
              });
          },done: function(res){
              if(!res.flag){
                  layer.msg(res.msg,{icon: 5,anim: 6});
              }else{
                  console.log(res);
                  $("#tbGoodsPath1").val(res.msg);
                  console.info($('#tbGoodsPath1').val());
              }
          }
      });
    //自定义验证规则
    form.verify({
      orderNo: function(value){
        if(value.trim()==""){
          return "编号不能为空";
        }
      }
    });
    //数据表格实例化
    var tbWidth = $("#tableRes").width();
    var layTableId = "layTable";
    var tableIns = table.render({
      elem: '#dataTable',
      id: layTableId,
      data: viewObj.tbData,
      width: tbWidth,
      page: true,
      loading: true,
      even: false, //不开启隔行背景
      cols: [[
        // {title: '序号', type: 'numbers'},
        {field: 'sample', title: '样件名称', edit: 'text'},
        {field: 'design', title: '设计类型', edit: 'text'},
        {field: 'material', title: '材料类型', edit: 'text'},
        {field: 'technology', title: '工艺类型', edit: 'text'},
        {field: 'handle', title: '后处理要求', edit: 'text'},
        {field: 'number', title: '数量', edit: 'text'},
        {field: 'weight', title: '重量', edit: 'text',style:"background:red;"},
        {field: 'period', title: '工期', edit: 'text',style:"background:red;"},
        {field: 'foreign_prient', title: '外协打印', edit: 'text',style:"background:red;"},
        {field: 'foreign_handle', title: '外协处理', edit: 'text',style:"background:red;"}
        // {field: 'tempId', title: '操作', templet: function(d){
        //     return '<a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="del" lay-id="'+ d.tempId +'"><i class="layui-icon layui-icon-delete"></i>移除</a>';
        //   }}
      ]],
      done: function(res, curr, count){
        viewObj.tbData = res.data;
      }
    });

    //定义事件集合
    var active = {
      addRow: function(){	//添加一行
        var oldData = table.cache[layTableId];
        var newRow = {sample: '', design: '', material: '', technology: '',handle: '',number: ''};
        oldData.push(newRow);
        tableIns.reload({
          data : oldData
        });
      },
      updateRow: function(obj){
        var oldData = table.cache[layTableId];
        for(var i=0, row; i < oldData.length; i++){
          row = oldData[i];
          if(row.tempId == obj.tempId){
            $.extend(oldData[i], obj);
            return;
          }
        }
        tableIns.reload({
          data : oldData
        });
      },
      removeEmptyTableCache: function(){
        var oldData = table.cache[layTableId];
        for(var i=0, row; i < oldData.length; i++){
          row = oldData[i];
          if(!row || !row.tempId){
            oldData.splice(i, 1);    //删除一项
          }
          continue;
        }
        tableIns.reload({
          data : oldData
        });
      },
      // upload.render({
      //   elem: '#test3'
      //   ,url: 'upload'
      //   ,accept: 'file',
      //   before: function(obj){
      //     //预读，不支持ie8
      //     obj.preview(function(index, file, result){
      //       $('#demo2').find('img').remove();
      //       $('#demo2').append('<span class="x-red">已经上传</span>');
      //     });
      //   },done: function(res){
      //     if(!res.flag){
      //       layer.msg(res.msg,{icon: 5,anim: 6});
      //     }else{
      //       console.log(res);
      //       $("#file").val(res.msg);
      //       console.info($('#file').val());
      //     }
      //   }
      // });
      save: function(){
        // if(checkC() == false){
        //   return;
        // }
        var dataFrom = $("#saveForm").serializeArray();
        var jjj = serializeToObject(dataFrom);

        var taskDetails= JSON.stringify(table.cache[layTableId]);
        jjj.taskDetails = taskDetails;

        var eee = JSON.stringify(jjj);
        $.ajax({
          url: "save1",
          type: "post",
          // dataType:'json',
          // contentType: "application/json",
          async:false, traditional: true,
          data:jjj,
          success: function (data) {
            window.top.layer.msg("保存成功", {icon: 6, offset: 'rb', area: ['120px', '80px'], anim: 2});
            window.parent.location.reload();//刷新父页面
            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
            parent.layer.close(index);
          },
          error: function () {
            alert("保存失败");
          }
        })
      }
    }

    //激活事件
    var activeByType = function (type, arg) {
      if(arguments.length === 2){
        active[type] ? active[type].call(this, arg) : '';
      }else{
        active[type] ? active[type].call(this) : '';
      }
    }

    //注册按钮事件
    $('.layui-btn[data-type]').on('click', function () {
      var type = $(this).data('type');
      activeByType(type);
    });

    //监听select下拉选中事件
    form.on('select(type)', function(data){
      var elem = data.elem; //得到select原始DOM对象
      $(elem).prev("a[lay-event='type']").trigger("click");
    });

    //监听工具条
    table.on('tool(dataTable)', function (obj) {
      var data = obj.data, event = obj.event, tr = obj.tr; //获得当前行 tr 的DOM对象;
      console.log(data);
      switch(event){
        case "type":
          //console.log(data);
          var select = tr.find("select[name='type']");
          if(select){
            var selectedVal = select.val();
            if(!selectedVal){
              layer.tips("请选择一个分类", select.next('.layui-form-select'), { tips: [3, '#FF5722'] }); //吸附提示
            }
            console.log(selectedVal);
            $.extend(obj.data, {'type': selectedVal});
            activeByType('updateRow', obj.data);	//更新行记录对象
          }
          break;
        case "state":
          var stateVal = tr.find("input[name='state']").prop('checked') ? 1 : 0;
          $.extend(obj.data, {'state': stateVal})
          activeByType('updateRow', obj.data);	//更新行记录对象
          break;
        case "del":
          layer.confirm('真的删除行么？', function(index){
            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
            layer.close(index);
            activeByType('removeEmptyTableCache');
          });
          break;
      }
    });
  });
</script>

</body>

</html>
